# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import SignError, NotPayOrderError, ProcessedPayOrderError, NotResponsePayIdError
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '18578900938': {  # 远大_支付宝扫码H5_02
        'API_KEY': '3e3f86026886c13cbb08078c621e0565',
        'APP_KEY': 'e43c2353d5d1423495928ef1069ed6a0',
    },
    'gateway_web': 'https://s.starfireotc.com/payLink/web.html',
    'gateway_mobile': 'https://s.starfireotc.com/payLink/mobile.html',
}


# 回调的ip地址
# 220.128.122.203,203.69.59.11,103.123.2.79,59.124.0.138,3.113.1.244,
# 54.238.191.253,52.199.150.226,13.231.178.95,61.220.176.64 

def _get_pay_type(service):
    if service.endswith('web'):
        return 'gateway_web'
    return 'gateway_mobile'


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_app_key(mch_id):
    return APP_CONF[mch_id]['APP_KEY']


def _get_gateway(gateway):
    return APP_CONF[gateway]


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    sign = m.hexdigest().lower()
    return sign


# 请求签名格式
def generate_verify_sign(parameter, key):
    s = '%s%s%s%s%s%s%s' % (parameter['outOrderId'], parameter['customerAmount'],
                            parameter['pickupUrl'], parameter['receiveUrl'],
                            parameter['customerAmountCny'], parameter['signType'], key)
    return _gen_sign(s)


# 回调签名验证格式
def generate_notify_sign(parameter, key):
    s = '%s%s%s%s%s%s%s' % (parameter['customerAmount'], parameter['customerAmountCny'],
                            parameter['outOrderId'], parameter['orderId'],
                            parameter['signType'], parameter['status'], key)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    calculated_sign = generate_notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("xinghuopay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise SignError('sign not pass, data: %s' % params)


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='get'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    service = info.get('service')
    api_key = _get_api_key(app_id)
    app_key = _get_app_key(app_id)
    parameter_dict = OrderedDict((
        ('APPKey', app_key),
        ('customerAmount', ''),
        ('customerAmountCny', '%.2f' % float(pay_amount)),
        ('outOrderId', str(pay.id)),
        ('pickupUrl', '{}/pay/api/{}/xinghuopay/'.format(
            settings.NOTIFY_PREFIX, settings.RETURN_PATH)),
        ('receiveUrl', '{}/pay/api/{}/xinghuopay/{}'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('signType', 'MD5'),
    ))
    parameter_dict['sign'] = generate_verify_sign(parameter_dict, api_key)

    _LOGGER.info("xinghuopay create date: %s, order_id is: %s", json.dumps(parameter_dict),
                 parameter_dict['outOrderId'])

    html_text = _build_form(parameter_dict, _get_gateway(_get_pay_type(service)))
    cache_id = redis_cache.save_html(pay.id, html_text)
    url = settings.PAY_CACHE_URL + cache_id
    _LOGGER.info('xinghuopay to pay url: %s', url)
    return {'charge_info': url}


# success异步回调
def check_notify_sign(request, app_id):
    _LOGGER.info("xinghuopay notify body: %s", request.body)
    data = dict(request.POST.iteritems())
    _LOGGER.info("xinghuopay notify data: %s, order_id is: %s", data, data['outOrderId'])
    verify_notify_sign(data, _get_api_key(app_id))
    pay_id = data['outOrderId']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, pay object not exists, data: %s" % data)
        raise NotResponsePayIdError('xinghuopay event does not contain valid pay ID')
    pay = get_pay(pay_id)
    if not pay:
        raise NotPayOrderError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ProcessedPayOrderError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['status'])
    trade_no = data['outOrderId']
    total_fee = float(data['customerAmountCny'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee,
    }
    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == 'success':
        _LOGGER.info('xinghuopay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


# 暂时无订单查询接口
def query_charge(pay_order, app_id):
    pass
